package com.zhuanzhuan.hero.user.interceptor;

import com.zhuanzhuan.hero.user.util.EncryptDecryptUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.resultset.ResultSetHandler;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.springframework.stereotype.Component;

import java.sql.Statement;
import java.util.ArrayList;
import java.util.Objects;

/**
 * @ClassName interceptor
 * @Description  解密拦截器
 *   将查询结果的字段进行解密
 * @Author hanjunjun
 * @Date 2024/7/22 17:00
 */
@Component
@Intercepts({@Signature(type = ResultSetHandler.class, method = "handleResultSets", args = {Statement.class})})
@Slf4j
public class DecryptInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object resultObject = invocation.proceed();
        if (Objects.isNull(resultObject)) {
            return null;
        }
        if (resultObject instanceof ArrayList) {
            //基于selectList
            ArrayList resultList = (ArrayList) resultObject;
            if (!resultList.isEmpty() && EncryptDecryptUtil.needToDecrypt(resultList.get(0))) {
                for (Object result : resultList) {
                    //逐一解密
                    EncryptDecryptUtil.objectDecrypt(result);
                }
            }
        } else if (EncryptDecryptUtil.needToDecrypt(resultObject)) {
            //基于selectOne
            EncryptDecryptUtil.objectDecrypt(resultObject);
        }
        return resultObject;
    }

}
